import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { asyncRoutes } from './router'

const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      console.log(11)
      next('/')
      NProgress.done()
    } else {
      // 判断是否获取过资料
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getInfo')
        // console.log(roles.menus);
        const filterRoutes = asyncRoutes.filter((item) => {
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRouter', filterRoutes)
        router.addRoutes([
          ...filterRoutes,
          {
            path: '*',
            redirect: '/404',
            hidden: true
          }
        ])
        // router添加动态路由之后，需要转发一下
        next(to.path) // 目的是让路由拥有信息  router的已知缺陷
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
